// Node平台的身份认证中间件
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy;
const Strategy = require('passport-http-bearer').Strategy;
const jwt = require("jsonwebtoken");
let jwt_config = require('../config/jwt.config') 


// 初始化 passport 框架
const setup = (app, loginFunc, callback) => {
    // 1.用户名密码 登录策略
    passport.use(new LocalStrategy((username, password, done) => {
        // console.log(username,password)
        if (!loginFunc) return done('登录验证函数未设置!')

        loginFunc(username, password, (err, user) => {
            // console.log('有登录函数')
            if (err) return done(err)
            // 验证通过，
            return done(null, user)
        })
    }))

    //2. token验证策略
    passport.use(new Strategy((token ,done) => {
        // 验证token的有效性
        jwt.verify(token, jwt_config.secretKey, (err, payload) => {
            if (err) { return done('验证错误')}
            return done(null, payload)
        })
    }))

    // 3.初始化passport模块
	app.use(passport.initialize());

	if(callback) callback();
}

// 登录验证逻辑
const login = (req, res, next) => {
    passport.authenticate('local', (err, user, info) => {
        if (err) return res.sendResult(null, 400, err)
        if (!user) return res.sendResult(null, 400, '参数错误')
        // console.log('login', user)
        // 获取角色信息
        var token = jwt.sign({"uid": user.id, "rid": user.rid }, jwt_config.secretKey, { "expiresIn": jwt_config.expiresIn })
        user.Authrization = "Bearer " + token;
        // 将生成的Authrization返回给前端
        return res.sendResult(user, 200, "登录成功")
    }) (req, res, next)

}

// token验证函数
const tokenAuth = (req, res, next) => {
    passport.authenticate('bearer', { session: false }, (err, tokenData) => {
        if (err) return res.sendResult(null, 400, '无效token')
        if (!tokenData) return res.sendResult(null, 400, '无效token')
        req.userInfo = {}
        req.userInfo.uid = tokenData['uid']
        req.userInfo.rid = tokenData['rid']
        next()
    }) (req, res, next)
}

module.exports = {
    setup,
    login,
    tokenAuth
}
